<template>
	<div class="app-container">
		<jk-operation-card ref="box2" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button slot="reference" :disabled="!checkData.length" class="item-gap" type="primary" icon="el-icon-c-scale-to-original" @click="onSelectedBtn">
						<span>批量排产</span>
						<span style="font-size: 13px;font-weight: 700;">({{ checkData.length }}台)</span>
					</jk-button>
					<!--<jk-report-button :permission-prefix="prefix" class="margin-bottom-4" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :clearable="false" :option-list="workshopList" placeholder="区域" class="search-bar-item-size2 margin-5-0 item-gap" @change="onSearchBtn"></jk-select>
					<!--<jk-select v-model="searchParams.processCodes" :multiple="true" :collapse-tags="true" :clearable="true" value-key-name="code" :option-list="processList" placeholder="工序" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>-->
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种编号或名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @keyup.enter.native="onSearchBtn" />
					<jk-search-input v-model="searchParams.batchCode" placeholder="批号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @keyup.enter.native="onSearchBtn" />
					<!--<jk-search-input v-model="searchParams.productOrderCode" placeholder="生产订单号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @keyup.enter.native="onSearchBtn" />-->
					<!--<jk-search-input v-model="searchParams.prdNoticeCode" placeholder="生产通知单号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @keyup.enter.native="onSearchBtn" />-->
					<jk-search-input v-model="searchParams.nameOrCode" placeholder="机台编号或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @keyup.enter.native="onSearchBtn" />
					<jk-search-button class="margin-5-0 item-gap" @click="onSearchBtn"></jk-search-button>
					<jk-more-search @on-confirm="onSearchBtn" @on-reset="onResetSearchBtn">
						<el-row :gutter="16" class="flex-start-center-wrap">
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.frontSpinPlanCode" size="small" placeholder="前纺计划单号" clearable class="width-100-percent margin-5-0" @on-enter="onSearchBtn"></jk-search-input>
							</el-col>
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.prdNoticeCode" class="width-100-percent margin-5-0" clearable size="small" placeholder="生产通知单号" @on-enter="onSearchBtn"></jk-search-input>
							</el-col>
							<el-col :span="12">
								<jk-select v-model="moreSearchParams.processCodes" :multiple="true" class="width-100-percent margin-5-0" :collapse-tags="true" :clearable="true" value-key-name="code" :option-list="processList" placeholder="工序"></jk-select>
							</el-col>
						</el-row>
					</jk-more-search>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<jk-table
				ref="jkTable"
				border
				:cell-style="cellStyle"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 30"
				:checkbox-config="{strict: true}"
				:span-method="mergeColMethod"
				@checkbox-change="onCheckboxChange"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template v-if="item.keyName === 'taskDetailList'" slot="header">
						<div class="flex-start-center">
							<span class="margin-right-10">{{ item.title }}:</span>
							<stateLegend :state-list="openStateList"></stateLegend>
						</div>
					</template>
					<template slot-scope="scope">
						<div v-if="item.keyName === 'name'" class="flex-start-center">
							<!--<jk-state-bar :show-text="false" :state="scope.row.openingState" :state-list="openStateList"></jk-state-bar>-->
							<span>{{ scope.row.name }}</span>
						</div>
						<div v-else-if="item.keyName === 'taskDetailList'" class="flex-start-center">
							<task-list :data-list="scope.row.taskList"></task-list>
						</div>
						<div v-else-if="item.keyName === 'taskList'">
							<el-tag style="cursor: pointer;" class="width-100-percent" effect="plain" type="info" @click="onTaskBtn(scope)">
								待翻改：<i class="link-style">{{ scope.row.taskList ? scope.row.taskList.filter(x => x.openingState === 1).length : 0 }}</i>，
								待开台：<i class="link-style">{{ scope.row.taskList ? scope.row.taskList.filter(x => x.openingState === 2).length : 0 }}</i>，
								待了机：<i class="link-style">{{ scope.row.taskList ? scope.row.taskList.filter(x => x.openingState === 3).length : 0 }}</i>
							</el-tag>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-table-column fixed="left" type="checkbox" width="60" align="center"></vxe-table-column>

			</jk-table>

			<!-- 分页组件 -->
			<!--<footer ref="box3" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>-->
		</jk-card>
		<machine-task-dialog
			:data-item="selectMachineItem"
			:dialog-state="machineTaskDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></machine-task-dialog>
		<ratio-fore-spin-plan-dialog
			:dialog-state="ratioForeSpinPlanDialogState"
			@on-visible-change="onVisibleChangeOfRatioForeSpinPlanDialog"
			@on-confirm="onConfirmOfRatioForeSpinPlanDialog"
			@on-add="onAddBtn"
		></ratio-fore-spin-plan-dialog>
	</div>
</template>

<script>
    import machineTaskDialog from './machine-task-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import handlerCache from '../../../../mixins/handler-cache';
    import { productionPrdMachineView } from '../../../../api/production/xsOpen';
    import { openStateList } from '../../../../utils/jk/status-option-list';
    import taskList from './components/task-list';
    import ratioForeSpinPlanDialog from './components/radio-fore-spin-plan-dialog';
    import stateLegend from '../../afterSpinPrdSchedulingCenter/components/state-legend';

    export default {
        name: 'ForeSpinningPrdSchedulingCenter',
        components: {
            stateLegend,
            ratioForeSpinPlanDialog,
            taskList,
            machineTaskDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                prefix: 'production:prdNotice:process',
                apiItem: {
                    'page': productionPrdMachineView
                },
                processList: [],
                openStateList: [
                    { id: 2, name: '待开台', operationName: '待开台', color: '#2b85e4' },
                    { id: 3, name: '开台中', operationName: '待了机', color: '#0bab5b' }
                ],
                dataId: null,
                machineTaskDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                workshopList: [],
                selectMachineItem: {},
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    workshopId: null,
                    productNameOrCode: '',
                    productOrderCode: '',
                    batchCode: null,
                    nameOrCode: '',
                    auditState: null,
                    ifScheduling: true
                },
                moreSearchParams: {
                    frontSpinPlanCode: '',
                    prdNoticeCode: '',
                    processCodes: ['SM', 'BT', 'CS']
                },
                checkData: [],
                ratioForeSpinPlanDialogState: false
            };
        },
        methods: {
            cellStyle({ column, row }) {
                const styleConf = {};
                if (['processName', 'name'].includes(column.field)) {
                    if (row.processCode === 'SM') {
                        styleConf.backgroundColor = '#fef0f0';
                    } else if (row.processCode === 'BT') {
                        styleConf.backgroundColor = '#fdf6ec';
                    } else if (row.processCode === 'CS') {
                        styleConf.backgroundColor = '#ecf5ff';
                    }
                    if (column.field === 'processName') {
                        styleConf.fontSize = '14px';
                        styleConf.fontWeight = '700';
                    }
                    return styleConf;
                }
            },
            onResetSearchBtn() {
                Object.assign(this.$data.moreSearchParams, this.$options.data().moreSearchParams);
            },
            onConfirmOfRatioForeSpinPlanDialog(data) {
                this.ratioForeSpinPlanDialogState = false;
                this.$toOtherRouter({
                    name: 'editForeSpinningPlan',
                    query: {
                        id: data.id,
                        machineList: JSON.stringify(this.checkData)
                    }
                });
            },
            onVisibleChangeOfRatioForeSpinPlanDialog(e) {
                this.ratioForeSpinPlanDialogState = e;
            },
            onSelectedBtn() {
                this.ratioForeSpinPlanDialogState = true;
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                if (row.processName && column.property === 'processName') {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow.processName === row.processName) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.processName === row.processName) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onCheckboxChange(e) {
                this.checkData = e.records.map(x => {
                    return {
                        machineId: x.id,
                        machineCode: x.code,
                        machineName: x.name,
                        processId: x.processId,
                        processCode: x.processCode,
                        processName: x.processName
                    };
                });
            },
            onTaskBtn(scope) {
                this.selectMachineItem = JSON.parse(JSON.stringify(scope.row));
                this.machineTaskDialogState = true;
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onFinish() {
                this.machineTaskDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.machineTaskDialogState = e;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = { ...this.moreSearchParams, ...this.searchParams };
                this.apiItem.page(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res ? res.data.res.map(x => {
                            x.taskList = x.taskList ? x.taskList : [];
                            return x;
                        }) : [];
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.totalCount = 1;
                this.checkData = [];
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.ratioForeSpinPlanDialogState = false;
                this.$toOtherRouter({
                    name: 'addForeSpinningPlan',
                    query: {
                        machineList: JSON.stringify(this.checkData)
                    }
                });
                // this.machineTaskDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.machineTaskDialogState = true;
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem.exportExcel(params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                await this.getMenuColumnListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.processList = this.$store.state.user.userProcess.processList;
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            if (!this.searchParams.processCode) {
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
            }
            if (!this.searchParams.workshopId) {
                const workshopItem = this.workshopList.find(x => x.code === 'QF') || {};
                this.$set(this.searchParams, 'workshopId', workshopItem.id || this.$store.state.user.userWorkshop.defaultWorkshopId);
            }
            this.getDependentData();
        }
    };
</script>
